from menu_manager import MenuManager
from file_manager import FileManager
from student import Student

class Event:
    def __init__(self, type, data=0):
        self.type = type
        self.data = data


class EventListener:
    def fireEvent(self, event):
        pass


class EventManager:

    def __init__(self):
        self.listeners = []

    def add_listener(self, listener):
        self.listeners.append(listener)

    def fireEvents(self, event):
        for listener in self.listeners:
            listener.fireEvent(event)


class UserListener(EventListener):
    def __init__(self):

        self.file_manager = FileManager('data.txt')
        self.student_list = self.file_manager.read()

    def fireEvent(self, event):
        if event.type == 'add':
            self.add()
        elif event.type == 'update':
            self.update()
        elif event.type == 'sort':
            self.sort()
        elif event.type == 'query_by_id':
            self.query_by_id()
        elif event.type == 'query_all':
            self.query_all()
        elif event.type == 'delete':
            self.delete()
        elif event.type == 'quit':
            self.quit()

    def quit(self):
        self.file_manager.write_list(self.student_list)
        print('程序运行结束')

    def is_exists(self, id):
        exists = False

        for item in self.student_list:
            if item.id == id:
                exists = True

        return exists

    def add(self):

        # 对输入信息进行校验
        stu_id = input('请输入学号：')

        if self.is_exists(stu_id):
            print('id已存在！')
            return

        student = Student.init_from_input()
        student.id = stu_id

        self.student_list.append(student)

    def update(self):
        stu_id = input('请输入待更新学生学号：')
        if not self.is_exists(stu_id):
            print('id不存在！')
            return

        # remove stu from list
        for item in self.student_list:
            if item.id == stu_id:
                self.student_list.remove(item)

        stu = Student.init_from_input()
        stu.id = stu_id

        self.student_list.append(stu)

    def delete(self):
        student_id = input(f'请输入待删除学生学号: ')
        if not self.is_exists(student_id):
            print('id不存在！')
            return

        for item in self.student_list:
            if item.id == student_id:
                self.student_list.remove(item)

    def query_all(self):
        self.menu_manager.print_student_list(self.student_list)

    def sort(self):
        self.student_list.sort(key=lambda x: x.sum_score)

    def query_by_id(self):
        query_id = input('请输入id: ')

        if not self.is_exists(query_id):
            print('id不存在！')
            return

        for item in self.student_list:
            if item.id == query_id:
                self.menu_manager.print_student_list([item])

    def query_by_name(self):
        pass
